local skel = fk.CreateSkill {
  name = "#mahjong_que_rule&",
}

local KleeU = require "packages/gm_mahjong/utility/k_utility"
local U = require "packages/utility/utility"

Fk:loadTranslationTable{
  ["#mahjong_que_rule&"] = "麻将规则",
  ["@mahjong_last"] = "上一张牌：",
  ["@@Chow"] = "吃",
  ["@@Pung"] = "碰",
  ["@@Kong"] = "杠",
  ["@@Kong-Hide"] = "暗杠",
  ["@roomwind"] = "场风",
  ["@mahjong_seatwind"] = "自风",
  ["@banker"] = "庄家",
  ["@round_times"] = "轮数",
  ["@mahjong_point"] = "点数",
  ["card_river"] = "牌河"
}


--游戏开始时，确定场风和自风（标记）
skel:addEffect(fk.GameStart, {
  can_refresh = function (self, event, target, player, data)
    return target == player and player == player.room.players[1]
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    room:setBanner("@roomwind", "mahjong_z1")
    room:setBanner("roomwind", 1)
    room:setBanner("banker", room.players[1].id)
    room:setBanner("@banker", room.players[1]._splayer:getScreenName())
    room:setBanner("@round_times", 1)
    room:setBanner("sit", 1)
    for i,p in ipairs(room.players) do
      room:setPlayerMark(p,"@mahjong_seatwind","mahjong_z"..i)
      room:setPlayerMark(p,"mahjong_seatwind", i)
      room:setPlayerMark(p, "@mahjong_point", 25000)
      room:setPlayerMark(p, "next_comp_index", 1)
      room:handleAddLoseSkills(p, "mahjong_actv_skill&", nil, false, true)
      room:handleAddLoseSkills(p, "cheat", nil, false, true)
      room:handleAddLoseSkills(p, "mahjong_add_and_cancel_sign")
      room:handleAddLoseSkills(p, "mahjong_discard")
    end
  end,
})

--起始手牌数
skel:addEffect(fk.DrawInitialCards, {
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    data.num = 13
  end,
})

--跳过阶段，仅留下摸牌和出牌
skel:addEffect(fk.EventPhaseChanging, {
  can_refresh = function (self, event, target, player, data)
    local room = player.room
    if target == player and not data.skipped then
      if data.phase == Player.Start then return true
      elseif data.phase == Player.Judge then return true
      elseif data.phase == Player.Discard then return true
      elseif data.phase == Player.Finish then return true
      elseif data.phase == Player.Draw and player:getMark("cpk_turn") > 0 then
        room:setPlayerMark(player, "cpk_turn", 0)
        room:setPlayerMark(player, "cpk-turn", 1)
        return true
      elseif data.phase == Player.Draw and player:getMark("cpk_jump") > 0 then
        return true
      elseif data.phase == Player.Play and player:getMark("cpk_jump") > 0 then
        room:setPlayerMark(player, "cpk_jump", 0)
        return true
      end
    end
  end,
  on_refresh = function (self, event, target, player, data)
    data.skipped = true
  end,
})

--摸牌到14张，杠了则+1
skel:addEffect(fk.DrawNCards,{
  can_refresh = function (self, event, target, player, data)
    return target == player
  end,
  on_refresh = function (self, event, target, player, data)
    data.n = 1
  end,
})

skel:addEffect(fk.AfterCardsMove, {
  can_refresh = function (self, event, target, player, data)
    return true
  end,
  on_refresh = function (self, event, target, player, data)
    for _, move in ipairs(data) do
      if move.toArea == Player.Hand then
        for _, info in ipairs(move.moveInfo) do
          if Fk:getCardById(info.cardId):getMark("@@richi") > 0 then
            player.room:setCardMark(Fk:getCardById(info.cardId), "@@richi", 0)
          end
        end
      end
    end
  end
})

--出牌阶段保底必须打出牌
skel:addEffect(fk.EventPhaseEnd, {
  --因为要留出牌阶段用技能的空间，所以是阶段结束触发，不然可以阶段开始时触发，然后强制结束。
  can_refresh = function (self, event, target, player, data)
    if target == player and data.phase == Player.Play then
      local n = #player:getCardIds("h") - (#KleeU.getHandCards(player,3) / 4) - 13
      return n > 0
    end
  end,
  on_refresh = function (self, event, target, player, data)
    local room = player.room
    local c = Fk:getCardById(table.random(KleeU.getHandCards(player, 0)))
  
    room:useCard{
      card = c,
      from = player,
      tos = {player}
    } 
  end,
})

--出牌阶段出牌后，记录并结束
skel:addEffect(fk.AfterCardUseDeclared, {
  can_refresh = function(self, event, target, player, data)
    return target == player
  end,
  on_refresh = function(self, event, target, player, data)
    local room = player.room
    room:setBanner("mahjong_last", data.card.id)
    room:setBanner("@mahjong_last", data.card.name)
    room:showCards(data.card)
    player:addToPile("card_river", data.card, true, skel.name, player, room.players)
    if player:getMark("@@richi") > 0 then
      local hasRichiCard = false
      for _, cid in ipairs(player:getPile("card_river")) do
        if Fk:getCardById(cid):getMark("@@richi") then
          hasRichiCard = true
          break
        end
      end
      if not hasRichiCard then
        player.room:setCardMark(data.card, "@@richi", 1)
      end
    end
    player:endPlayPhase()
  end
})


--吃碰杠牌明置，不能打出或选择
skel:addEffect("visibility",{
  card_visible = function(self, player, card)
    if KleeU.getCardCPK(card) > 0 then
      return true
    end
  end
})
--
--skel:addEffect("filter",{
--  global = true,
--  card_filter = Util.TrueFunc,
--  view_as = function (self, player, card)
--    return Fk:cloneCard(card.name, card.suit+5, card.number+13)
--  end
--})
--
skel:addEffect("prohibit", {
  prohibit_use = function(self, player, card)
    if KleeU.getCardCPK(card) > 0 then
      return true
    end
  end
})

skel:addEffect(fk.TurnStart, {
  can_refresh = function (self, event, target, player, data)
    return player == target and player:getMark("jump_round") > 0
  end,
  on_refresh = function (self, event, target, player, data)
    player.room:setPlayerMark(player, "jump_round", 0)
    player.room:endTurn()
  end
})

--吃碰杠
skel:addEffect(fk.CardUseFinished, {
  mute = true,
  can_trigger = function (self, event, target, player, data)
    return player == target
  end,
  on_cost = Util.TrueFunc,
  on_use = function (self, event, target, player, data)
    local room = player.room
    local targets = table.simpleClone(player.room.alive_players)
    table.removeOne(targets, player)
    --构建req
    local req = Request:new(targets, "AskForUseActiveSkill")
    req.focus_text = "#mahjong_que_rule&"
    local dat = {"mahjong_trig_skill", "", true, {}}
    for _, p in ipairs(targets) do
      req:setData(p, dat)
    end
    req:ask()
    local responsers = {} ---@type any[]
    local r
    for _, p in ipairs(targets) do
      r = req:getResult(p)
      if r ~= "" then
        r.who = p
        if #responsers == 0 then
          table.insert(responsers, r)
        elseif r.interaction_data == "interaction_rong" then
          if responsers[1].interaction_data == "interaction_rong" then
            table.insert(responsers, r)
          else
            responsers[1] = r
          end
        elseif r.interaction_data == "interaction_pung" or r.interaction_data == "interaction_kong" then
          if responsers[1].interaction_data ~= "interaction_rong" then
            responsers[1] = r
          end
        elseif r.interaction_data == "interaction_chow" then
          if responsers[1].interaction_data ~= "interaction_rong" and r.interaction_data ~= "interaction_pung" and r.interaction_data ~= "interaction_kong"  and req.winners[1] == p then
            responsers[1] = r
          end
        end
      end
    end
    if #responsers == 1 then
      local response = responsers[1]
      local cpk = KleeU.ifCardCanCPK(response.who, data.card.id)
      local not_win = true
      if response.interaction_data == "interaction_chow" then
        room:doIndicate(player, response.who)
        if #cpk.C == 1 then
          for _, cid in ipairs(cpk.C[1]) do
            room:setCardMark(Fk:getCardById(cid), "@@Chow", 1)
          end
        else
          local listNames = {}
          for index, _ in ipairs(cpk.C) do
            table.insert(listNames, "组合"..index)
          end
          local listName = U.askForChooseCardList(room, response.who, listNames, cpk.C, 1, 1, "@@Chow", "@@Chow", false, false)
          for _, cid in ipairs(cpk.C[table.indexOf(listNames, listName[1])]) do
            room:setCardMark(Fk:getCardById(cid), "@@Chow", 1)
          end
        end
        room:obtainCard(response.who, data.card.id, true, fk.ReasonJustMove, response.who, skel.name, "@@Chow")
      elseif response.interaction_data == "interaction_pung" then
        room:doIndicate(player, response.who)
        room:obtainCard(response.who, data.card.id, true, fk.ReasonJustMove, response.who, skel.name, "@@Pung")
        for _, cid in ipairs(cpk.P[1]) do
          room:setCardMark(Fk:getCardById(cid), "@@Pung", 1)
        end
      elseif response.interaction_data == "interaction_kong" then
        room:doIndicate(player, response.who)
        room:obtainCard(response.who, data.card.id, true, fk.ReasonJustMove, response.who, skel.name, "@@Kong")
        for _, cid in ipairs(cpk.K[1]) do
          room:setCardMark(Fk:getCardById(cid), "@@Kong", 1)
        end
      elseif response.interaction_data == "interaction_rong" then
        not_win = false
      end
      if not_win then
        local jump = response.who ---@type ServerPlayer
        jump = jump:getLastAlive()
        while true do
          if jump == room.current then
            break
          else 
            room:setPlayerMark(jump, "jump_round", 1)
            jump = jump:getLastAlive()
          end
        end
      end
    end
    if #responsers >= 1 and responsers[1].interaction_data == "interaction_rong" then
      KleeU.win(table.map(responsers, function (resp)
        return resp.who
      end), false)
    end
  end
})


return skel